<?php
//
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'main';
if($_RQ['op']=='main'){
	$id=$_RQ['id'];
	if(!$id){
		exi('请选择优惠券','error');
	}
	$coupon=$this->model('coupon')->intcoupon($id);
	if($coupon['issendtime']){
		$coupon['sendtime']=json_decode($coupon['sendtime'],true);
		if($coupon['sendtime']['tstart']>time()){
					$coupon['issend']=0;
					$coupon['etime']=$coupon['sendtime']['tstart'];
		}elseif($coupon['sendtime']['tstart']<time() && $coupon['sendtime']['tend']>time()){
					$coupon['issend']=1;
					$coupon['etime']=$coupon['sendtime']['tend'];
		}elseif($coupon['sendtime']['tend']<time()){
					$coupon['issend']=2;
		}
	}else{
		$coupon['issend']=1;
	}
	if ($coupon['limitgoodtype'] != 0) {
			if (!empty($coupon['limitgoodids'])) {
				$limitgoodids = str_array($coupon['limitgoodids']);
			}
			$goods = pdo_getall('jy_weishop_goods',array('uniacid' => $_SESSION['uniacid'],'id'=>$limitgoodids),'title');
		}
		if ($coupon['islimitlevel'] == 1) {
			if (!empty($coupon['memberlevels'])) {
				
				$where = 'and id in(' . implode(',',str_array($coupon['memberlevels'])) . ')';
			}

			$level = pdo_fetchall('select `title` from ' . tablename('jy_weishop_member_level') . ' where uniacid=:uniacid ' . $where, array(':uniacid' => $_SESSION['uniacid']), 'id');
		}

		if ($coupon['limitgoodcatetype'] != 0) {
			if (!empty($coupon['limitgoodcateids'])) {
				$limitgoodcateids = str_array($coupon['limitgoodcateids']);
			}
			$group = pdo_getall('jy_weishop_goods_group',array('uniacid' => $_SESSION['uniacid'],'id'=>$limitgoodcateids));
		}
	if($coupon['getmax'] > 0){
		$num = pdo_count('jy_weishop_coupon_getlog',array('uniacid' => $_SESSION['uniacid'],'mid'=>$_SESSION['uid'],'couponid'=>$id));
		if($num<$coupon['getmax']){
			$coupon['canget'] = 1;
		}else{
			$coupon['canget'] = 0;
		}
	}else{
		$coupon['canget'] = 1;
		$coupon['getmax'] = '不限';
	}
	if($coupon['islimitlevel']){
		if (!empty($coupon['memberlevels'])) {
				$memberlevels = explode(';',$coupon['memberlevels']);
		}
		$userlevel = pdo_getcolumn('jy_weishop_member',array('uniacid' => $_SESSION['uniacid'],'mid'=> $_SESSION['uid']),'level');
		$coupon['pass'] =  in_array($userlevel,$memberlevels);
	}else{
		$coupon['pass'] = 1;
	}
	$coupon['gettypestr'] = '领券';
	$return['coupon_setting']=$this->plugin_setting('coupon');
	$return['goods']=$goods;
	$return['level']=$level;
	$return['group']=$group;
	$return['coupon']=$coupon;
	exi($return);
}
//领券优惠券
if($_RQ['op']=='getcoupon'){
	$post=get_postdata();
	$id=$post['id'];
	$this->model('coupon')->getcoupon($id);
	if($post['nogoback']){
		exi('成功领取优惠券.');
	}else{
		exi('成功领取优惠券！','','coupon.index/');
	}
}
?>